package com.kcs.fxmargin.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.kcs.common.utils.ConnectionUtils;
import com.kcs.common.utils.Constant;
import com.kcs.common.utils.OIDGenerator;
import com.kcs.fxmargin.bo.ValidateSettlementBO;
import com.kcs.fxmargin.dao.DealsDao;
import com.kcs.fxmargin.model.TDeals;
import com.kcs.fxmargin.model.TDealsSettle;

public class DealsService {
	
	DealsDao dao = new DealsDao();
	
	public List<ValidateSettlementBO> search(TDeals deals) throws Exception {
		
		Connection conn 				= null;
		PreparedStatement pstm 			= null;
		ResultSet rs					= null;
		List<ValidateSettlementBO> validateSettlementBOList = new ArrayList<ValidateSettlementBO>();
		
		try{
			conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO); // get connection fxmargin from mssql
			validateSettlementBOList = dao.search(conn, pstm, rs, deals);
			
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			if(conn != null ) conn.close();
			if(pstm != null ) pstm.close();
			if(rs   != null ) rs.close();
		}
		
		return validateSettlementBOList;
	}
	
	public String update(List<TDealsSettle> modelList) throws Exception {
		
		Connection conn 				= null;
		PreparedStatement pstm 			= null;
		String result					= "s";
		try{
			conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO); // get connection fxmargin from mssql
			
			stop:
			for(TDealsSettle deals: modelList){
				if("s".equals(result)){
					
					if(deals.getId() != null && !"".equals(deals.getId())){
						result = dao.update(conn, pstm, deals);
					} else {
						deals.setId(OIDGenerator.create());
						result = dao.insert(conn, pstm, deals);
					}
					
				} else {
					break stop;
				}
			}
			
			conn.commit();
		} catch (Exception e){
			e.printStackTrace();
			conn.rollback();
		} finally {
			if(conn != null ) conn.close();
			if(pstm != null ) pstm.close();
		}
		return result;
	}
}
